package com.hao.netty.server;

import com.hao.netty.handler.ChatServerInitializer;
import com.hao.netty.listener.ChannelCloseListener;
import com.hao.netty.listener.ServerStartListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2021/11/30 12:21
 */
public class ChatNettyServer {


    private static final Integer PORT = 6789;

    private static final Integer SO_BACKLOG = 128;

    public void run(){
        // 创建两个循环线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建netty服务端的启动器
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            //对serverBootstrap进行配置
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,SO_BACKLOG)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChatServerInitializer());

            //启动绑定
            ChannelFuture startFuture = serverBootstrap.bind(PORT).sync();
            startFuture.addListener(new ServerStartListener());

            //对关闭的管道进行监听
            ChannelFuture channelCloseFuture = startFuture.channel().closeFuture().sync();
            channelCloseFuture.addListener(new ChannelCloseListener());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ChatNettyServer().run();
    }
}
